package com.example.project.projectspringcloud.controller.admin.user;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Area;
import com.example.project.projectspringcloud.entity.user.Role;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.service.sys.SysAreaService;
import com.example.project.projectspringcloud.service.user.PermissionService;
import com.example.project.projectspringcloud.service.user.UserService;
import com.example.project.projectspringcloud.utils.StringUtil;
import com.example.project.projectspringcloud.utils.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Locale;

/**
 * 用户管理
 */
@Api(tags = "用户管理控制器")
@Controller
@RequestMapping(value = "/admin/user")
public class AdminUserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private SysAreaService sysAreaService;

    @ApiOperation(value = "列表页面", notes = "返回列表页面")
    @RequestMapping(value = {"", "/list"}, method = {RequestMethod.POST, RequestMethod.GET})
    public String list(User user, Page page, Model model) throws Exception {
        user.setMaxLevel(WebUtil.getCurrentUser().getMaxRoleLevel());
        List<User> userList = userService.listWithPrivate(page, user);
        model.addAttribute("page", new Page<User>(userList));
        model.addAttribute("user", user);
        model.addAttribute("roleList", permissionService.roleList(new Role()));
        return "admin/user/user-list";
    }

    @ApiOperation(value = "删除", notes = "delete by id/ids")
    @DeleteMapping(value = "/delete/{ids}")
    @ResponseBody
    public RespBody delete(@ApiParam(value = "字符串ID数组 1,2,3...") @PathVariable("ids") String ids) {
        if (StringUtils.isBlank(ids)) {
            return RespBody.error(Constants.Message.PARAM_INVALID);
        }
        Integer[] idarr = StringUtil.split(ids, ",");
        if (!userService.delete(idarr)) {
            return RespBody.error(Constants.Message.DELETE_FAILED);
        }
        return RespBody.ok(Constants.Message.DELETE_SUCCESS);
    }

    @ApiOperation(value = "获取表单", notes = "获取单个信息表单返回")
    @GetMapping(value = "/form")
    public String form(@RequestParam(value = "id", required = false) Integer id, Model model) throws Exception {
        if (id != null) {
            User user = userService.getWithPrivate(new User(id));
            model.addAttribute("user", user);
        }

        List<Role> roles = permissionService.roleList(new Role());
        model.addAttribute("roles", roles);

        Area entity = new Area();
        List<Area> areas = sysAreaService.list(entity, null);
        model.addAttribute("areas", areas);
        return "admin/user/user-form";
    }

    @ApiOperation(value = "保存用户信息", notes = "根据ID判断是否存在, 执行是否更新/插入")
    @PostMapping(value = "/save")
    @ResponseBody
    public RespBody save(@Validated User user, BindingResult bindingResult, Locale locale) throws Exception {
        try {
            if (bindingResult.getErrorCount() > 0) {
                return RespBody.error(RespBody.ERROR_VALIDATE_CODE, super.translateI18N(bindingResult));
            }

            boolean result = userService.save(user);
            if (!result) {
                return RespBody.error(Constants.Message.SAVE_FAILED);
            }
        } catch (OperationException e) {
            return RespBody.error(e.getMessage());
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }

    @ApiOperation(value = "是否在首页显示", notes = "切换是否在首页显示")
    @PostMapping(value = "/change_show")
    @ResponseBody
    public RespBody changeshow(User user) throws Exception {
        try {
            boolean result = userService.changeShow(user);
            if (!result) {
                return RespBody.error(Constants.Message.SAVE_FAILED);
            }
        } catch (OperationException e) {
            return RespBody.error(e.getMessage());
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }

    @ApiOperation(value = "通过账号查询用户是否存在", notes = "返回是否")
    @GetMapping(value = "/get_by_account/{userAccount}")
    @ResponseBody
    public Boolean getByAccount(@ApiParam(name = "userAccount", value = "用户账号") @PathVariable("userAccount") String userAccount) throws Exception {
        try {
            User user = new User();
            user.setAccount(userAccount);
            user = userService.get(user);
            if (user != null && StringUtils.isNotBlank(user.getNickname())) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
